const puppeteer = require('puppeteer');
const { mn } = require("./config/default");
const srcToimg = require('./helper/srcToimg');
(async () => {
    const browser = await puppeteer.launch(
        {
            headless: false,     //有浏览器界面启动
            slowMo: 100,         //放慢浏览器执行速度，方便测试观察
        }
    );
    const page = await browser.newPage();
    await page.goto('https://image.baidu.com/');
    console.log('go to https://www.baidu.com');

    await page.setViewport({
        width: 1920,
        height: 2080
    });
    console.log('reset viewport');

    // 用输入框id获取输入框，聚焦
    await page.focus("#kw")
    //模拟键盘输入
    await page.keyboard.sendCharacter('风景');
    // 用搜索按钮的class类名 进行点击事件
    await page.click(".s_newBtn")

    //等待网页加载完成 load
    page.on('load', async () => {
        //获取图片 src列表
        const srcs = await page.evaluate(() => {
            const images = document.querySelectorAll('img.main_img');
            return Array.prototype.map.call(images, img => img.src)
        });
        console.log(`get${srcs.length} images`);
        // 保存 src

        srcs.forEach(async src => {
        
            await srcToimg(src, mn)

        });
        await browser.close();
    });

})();